#COMET
import simplejson
import time
from datetime import datetime
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django import forms
from models import Message

class MsgForm(forms.ModelForm):
    class Meta:
        model = Message
        exclude = ('time',)
        
def json_response(obj='', status=200):
    return HttpResponse(simplejson.dumps(obj), status=status)

def chat(request):
    return render_to_response('chat_window.html', {'form':MsgForm()})

def update(request):
    last_update = request.session.get('last_update', datetime.now())

    def format_msg(msg):
        return '<li><span class="date">%s</span> %s</li>' % (msg.time.strftime('%H:%I:%S'), msg.text)
        
    def check_msgs():
        while True:
            msgs = Message.objects.filter(time__gte=last_update).order_by('-time')
            if msgs:
                request.session['last_update'] = datetime.now()
                request.session.save() #el session middleware ya se ejecuto.
                yield ''.join( format_msg(m) for m in msgs )
                raise StopIteration()
            else:
                time.sleep(0.2)
                yield ''
    return HttpResponse(check_msgs())

def write(request):
    form = MsgForm(request.GET)
    if form.is_valid():
        msg = form.save()
        return json_response({'msg_id':msg.id})
    else:
        return json_response(status=500)
    
    
